package com.plat.api.api.action;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.plat.api.common.RedisKey;
import com.plat.api.common.RespCode;
import com.plat.api.exception.PlatException;
import com.plat.api.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: shish
 * Date: 2020/5/10
 * Time: 1:13
 * Description: No Description
 */
@Service
public class CheckCodeAction {
    private static Integer timeout = 60;
    @Autowired
    private RedisCache redisCache;

    public JSONObject getCheckCode(JSONObject jsObject) {
        JSONObject jsonObject = jsObject.getJSONObject("body");
        String phone = jsonObject.getString("phone");
        String code = "";
        String url = "";
        if (phone != null) {
            try {
                //发送验证码 查询手机是否可发,超出限制不可再发，防止短信轰炸
                code = "手机验证码";
            } catch (Exception platException) {
                throw new PlatException(RespCode.SEND_SMS_LIMIT.getCode(), RespCode.SEND_SMS_LIMIT.getError_msg());
            }
        } else {
            code = get().get("code");
            url = get().get("url");
        }
        JSONObject json = new JSONObject();
        redisCache.setCacheObject(RedisKey.checkKey + code, code, timeout, TimeUnit.SECONDS);
        json.put("timeout", timeout);
        jsObject.put("url", StrUtil.toString(url));
        return json;
    }

    public Map<String, String> get() {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String path = "d:/line.png";
        lineCaptcha.write(path);
        File file = new File(path);
        //上传至服务端返回url
        Map map = new HashMap();
        map.put("code", lineCaptcha.getCode());
        map.put("url", "url");
        return map;
    }
}
